﻿using System.Data.SqlClient;
using NAnt.Core.Attributes;

namespace ECM7.NantContrib.Tasks.SqlServer
{
	/// <summary>
	/// Резервное копирование базы данных MSSQL
	/// </summary>
	[TaskName("backupDatabase")]
	public class BackupDatabaseTask : BaseSqlServerTask
	{
		/// <summary>
		/// Выполнение необходимых действий
		/// </summary>
		protected override void ExecuteTask()
		{
			SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder
			{
				InitialCatalog = Database,
				DataSource = Instance,
				UserID = User ?? string.Empty,
				Password = Password ?? string.Empty,
				IntegratedSecurity = IntegratedSecurity
			};

			using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
			{
				connection.Open();
				using (SqlCommand command = connection.CreateCommand())
				{
					command.CommandText =
						"BACKUP DATABASE @database TO DISK = @filename " +
						"WITH NOFORMAT, INIT, NAME = N'Full Database Backup', " +
						"SKIP, NOREWIND, NOUNLOAD, STATS = 10;";

					command.Parameters.AddWithValue("@database", Database);
					command.Parameters.AddWithValue("@filename", FileName);
					
					ExecuteCommand(command);
				}
			}
		}

		/// <summary>
		/// Файл для сохранения результата
		/// </summary>
		[TaskAttribute("backupFileName", Required = true), StringValidator(AllowEmpty = false)]
		public string FileName { get; set; }
	}
}

